import { useRequest } from "../../../../utils/request";

const WeValidator = require('../../../../package/we-validator.min')

Component({
    properties: {},
    data: {
        phone: ''
    },
    methods: {
        onLoad(options) {
            this.validatorInstance = new WeValidator({
                rules: {
                    name: {
                        required: true,
                    },
                    account: {
                        required: true,
                    },
                    phone: {
                        required: true,
                        mobile: true
                    },
                    sms_code: {
                        required: true,
                    },
                },
                messages: {
                    name: {
                        required: '请输入姓名',
                    },
                    account: {
                        required: '请输入支付宝账号',
                    },
                    phone: {
                        required: '请输入手机号',
                        mobile: '请输入正确的手机号'
                    },
                    sms_code: {
                        required: '请输入验证码',
                    },
                },
            })

            if (options.edit === '1') {
                this.request = new useRequest('api/editalipayaccount', {
                    hold: true
                }, this)
            } else {
                this.request = new useRequest('api/bindalipayaccount', {
                    hold: true
                }, this)
            }

            this.getCode = new useRequest('api/verifycode', {
                hold: true,
                loading: 'codeLoading'
            }, this)
        },

        startTimeout() {
            this.setData({
                second: 59
            })
            this.timeout = setInterval(() => {
                this.setData({
                    second: this.data.second - 1
                })
                if (this.data.second <= 0) {
                    clearInterval(this.timeout)
                }
            }, 1000)
        },

        getPhoneCode() {
            if (
                WeValidator.checkValue('required', this.data.phone) &&
                WeValidator.checkValue('mobile', this.data.phone, true)
            ) {
                this.getCode.run({ phone: this.data.phone }).then(() => {
                    this.startTimeout()
                })
            }
        },

        submit(e) {
            const value = e.detail.value

            if (this.validatorInstance.checkData(value)) {
                this.request.run({
                    ...value,
                }).then(() => {
                    wx.showToast({
                        title: '绑定成功'
                    })
                    wx.navigateBack()
                })
            }
        },
    }
});
